const express = require("express");
const router = express.Router();
const db = require("../utils/db");
const dayjs = require("dayjs");

// 获取所有车辆信息
router.get("/", async (req, res) => {
  try {
    const [rows] = await db.query("SELECT * FROM hc_activation_daily");
    rows.forEach((item) => {
      item.create_time = item.create_time
        ? dayjs(item.create_time).format("YYYY-MM-DD HH:mm:ss")
        : null;
    });
    res.json({
      status:"OK",
      code: 200,
      data: {
        rows,
      },
    });
  } catch (error) {
    res.status(500).json({ message: "数据库查询错误", error: error.message });
  }
});


// 获取用车报告信息 根据传入的时间
router.post("/report", async (req, res) => {
  try {
    const { vinCode, date } = req.body;
    
    // 验证必需参数
    if (!vinCode || !date) {
      return res.status(400).json({ 
        status: "ERROR",
        code: 400,
        message: "缺少必需参数：vinCode 和 date" 
      });
    }
    
    // 计算7天前的日期
    const endDate = dayjs(date);
    const startDate = endDate.subtract(7, 'day');
    
    // 构建SQL查询，查询指定vin_code且在时间范围内的数据
    const query = `
      SELECT * FROM vehicle_driving_records 
      WHERE vin_code = ? 
      AND record_date >= ? 
      AND record_date <= ?
      ORDER BY record_date DESC
    `;
    
    const [rows] = await db.query(query, [
      vinCode,
      startDate.format('YYYY-MM-DD HH:mm:ss'),
      endDate.format('YYYY-MM-DD HH:mm:ss')
    ]);
    
    // console.log(rows, 'rows');
    
    // 格式化时间字段
    rows.forEach((item) => {
      item.record_date = item.record_date
        ? dayjs(item.record_date).format("YYYY-MM-DD HH:mm:ss")
        : null;
    });
    
    res.json({
      status: "OK",
      code: 200,
      data: {
        rows,
        query_info: {
          vinCode,
          date_range: {
            start: startDate.format('YYYY-MM-DD HH:mm:ss'),
            end: endDate.format('YYYY-MM-DD HH:mm:ss')
          },
          total_records: rows.length
        }
      },
    });
  } catch (error) {
    res.status(500).json({ 
      status: "ERROR",
      code: 500,
      message: "数据库查询错误", 
      error: error.message 
    });
  }
});

// 获取单个车辆信息
router.get("/:id", (req, res) => {
  res.json({ message: `获取ID为${req.params.id}的车辆信息` });
});

// 创建车辆信息
router.post("/", (req, res) => {
  res.json({ message: "创建新的车辆信息", data: req.body });
});

// 更新车辆信息
router.put("/:id", (req, res) => {
  res.json({ message: `更新ID为${req.params.id}的车辆信息`, data: req.body });
});

// 删除车辆信息
router.delete("/:id", (req, res) => {
  res.json({ message: `删除ID为${req.params.id}的车辆信息` });
});

module.exports = router;
